import { FC, useEffect, useState } from "react";
import { ElementItem } from "../../types/business";
import { Modal, Checkbox, Form, Slider, Image } from "antd";
import { clone, cloneDeep, find, get, isArray } from "lodash";
import { EditOutlined } from "@ant-design/icons";
import dialog from "../Dialog";

type Item = ElementItem;

const ElementSelector: FC<{
  flag: number;
  list: Item[];
  setList: (v: any[]) => void;
  value: any[];
  onChange?: (v: any[]) => void;
}> = ({ flag, list, setList, value, onChange }) => {
  const [innerValue, setInnerValue] = useState<any[]>([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [listChild, setListChild] = useState<Item>();
  useEffect(() => {
    if (!!flag) {
      setIsModalOpen(true);
    }
  }, [flag]);

  useEffect(() => {
    if (isModalOpen) {
      setInnerValue(cloneDeep(value))
    }
  }, [isModalOpen, value])
  useEffect(() => {
    if (get(list, "length", 0) !== 0) {
      setListChild(list[0]);
    }
  }, [list]);
  const hasItem = (item: Item) => {
    if (
      !isArray(item.sub_tag_list) ||
      get(item, "sub_tag_list.length", 0) === 0
    ) {
      return innerValue.includes(item.id);
    }
    return item.sub_tag_list.every((i) => innerValue.includes(i.id));
  };

  const handleChange = (item: Item) => {
    const itemId =
      get(item, "sub_tag_list.length", 0) > 0
        ? item.sub_tag_list.map((v) => v.id)
        : [item.id];
    if (hasItem(item)) {
      setInnerValue?.(innerValue.filter((v) => !itemId.includes(v)));
    } else {
      setInnerValue?.([...new Set([...innerValue, ...itemId])]);
    }
  };

  const editorItem = (item: Item) => {
    dialog({
      title: "编辑元素",
      content: (
        <Form
          initialValues={{
            threshold: item.threshold,
            score: item.score,
          }}
        >
          <div className="text-center">{item.title}</div>
          <div className="my-[10px] text-center">
            <Image width={150} height={150} src={item.url} className="object-contain" />
          </div>
          <Form.Item label="阈值" name="threshold">
            <Slider min={0} max={1} step={0.01} />
          </Form.Item>
          <Form.Item label="分数" name="score">
            <Slider min={0} max={10} />
          </Form.Item>
        </Form>
      ),
      onOk(value, hidden) {
        item.score = value.score;
        item.threshold = value.threshold;
        hidden();
        setList(cloneDeep(list))
      }
    });
  };

  return (
    <Modal
      title="元素列表"
      open={isModalOpen}
      onCancel={() => {
        setIsModalOpen(false);
      }}
      onOk={() => {
        onChange?.(cloneDeep(innerValue))
        setIsModalOpen(false)
      }}
      bodyStyle={{ padding: 0 }}
      width={1160}
    >
      <div className="flex h-[600px] m-[-20px] mt-[20px]" style={{ borderTop: '1px solid #000' }}>
        <div className="h-full overflow-y-auto" style={{ borderRight: '1px solid #000' }}>
          <div className="pb-[20px]">
            {list.map((item) => (
              <div
                className="m-[15px] flex w-[200px] cursor-pointer flex-col-reverse bg-contain bg-center bg-no-repeat"
              >
                <div
                  className="flex hover:bg-[#000]/[.5] p-[5px] hover:text-[#fff]"
                  onClick={(e) => {
                    setListChild(item);
                  }}
                >
                  <Checkbox checked={hasItem(item)} className="mr-[5px]" onClick={(e) => {
                    handleChange(item);
                  }} />
                  <div className="flex-1 truncate">{item.title}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className="h-full flex-1 overflow-y-auto">
          <div>
            {listChild?.sub_tag_list?.map?.((item) => (
              <div
                className="m-[15px] inline-flex h-[200px] w-[200px] cursor-pointer flex-col-reverse bg-contain bg-center bg-no-repeat"
                style={{ backgroundImage: `url(${item.url})` }}
                onClick={(e) => {
                  handleChange(item);
                }}
              >
                <div
                  className="flex bg-[#000]/[.5] p-[5px] text-[#fff]"
                >
                  <Checkbox checked={hasItem(item)} className="mr-[5px] pointer-events-none"/>
                  <div className="flex-1 truncate">{item.title}</div>
                  <EditOutlined
                    className="cursor-pointer"
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      editorItem(item)
                    }}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default ElementSelector;
